package uk.co.ianadie.tapsaff;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;

import com.bugsense.trace.BugSenseHandler;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

/**
 * Created by Ian on 04/06/13.
 */
public class UpdateWidgetService extends Service implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, TapsAffCallbackListener, LocationListener {
	private int[] allWidgetIds;
	private LocationClient myLocationClient;
	Location myLocation;
	SharedPreferences settings;
	int widgetSize;

	@Override
	public void onStart(Intent intent, int startId) {
		settings = PreferenceManager.getDefaultSharedPreferences(this);
		allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
		widgetSize = intent.getIntExtra("Size", 0);
		BugSenseHandler.initAndStartSession(this, settings.getString("bugsense_api_key", ""));

		if(settings.getLong("updatedTime", 0) < System.currentTimeMillis() - TapsAff.CACHE_TIME) {
			// more than one hour ago, get new values
			myLocationClient = new LocationClient(this, this, this);
			myLocationClient.connect();
		} else {
			this.updateWidgetViews(null);
		}

		stopSelf();
	}

	private class GetLocationTask extends AsyncTask {

		@Override
		protected Object doInBackground(Object... params) {

			myLocationClient = new LocationClient(UpdateWidgetService.this, UpdateWidgetService.this, UpdateWidgetService.this);
			myLocationClient.connect();

			return null;
		}
	}

	public void updateWidgetViews(Object result) {
		int tapsAffTemp = Integer.parseInt(settings.getString("tapsAffTemp", "17"));
		int currentTemp;
		
		if(settings.getString("tempUnit", TapsAff.CELSIUS).equals(TapsAff.CELSIUS)) {
			currentTemp = settings.getInt("tempC", 17);
		} else {
			currentTemp = settings.getInt("tempF", 63);
		}

		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(UpdateWidgetService.this.getApplicationContext());

		String newText;
		SharedPreferences.Editor editor = settings.edit();
		Bitmap newBitmap;

		if(currentTemp<tapsAffTemp) {
			if(widgetSize == TapsAff.SIZE_LARGE)
				newText = "taps oan";
			else
				newText = "oan";
			editor.putBoolean("tapsAff", false);
			if(settings.getString("textColour", "Light").equals("Light"))
				newBitmap = BitmapFactory.decodeResource(this.getApplicationContext().getResources(), R.drawable.tapsoanwhite);
			else
				newBitmap = BitmapFactory.decodeResource(this.getApplicationContext().getResources(), R.drawable.tapsoan);
		} else {
			if(widgetSize == TapsAff.SIZE_LARGE)
				newText = "taps aff";
			else
				newText = "aff";
			editor.putBoolean("tapsAff", true);
			if(settings.getString("textColour", "Light").equals("Light"))
				newBitmap = BitmapFactory.decodeResource(this.getApplicationContext().getResources(), R.drawable.tapsaffwhite);
			else
				newBitmap = BitmapFactory.decodeResource(this.getApplicationContext().getResources(), R.drawable.tapsaff);		
		}
		editor.commit();

		Log.i(TapsAff.LOG_TAG, "Current temerature is "+currentTemp+", it is "+newText+"!");

		for (int widgetId : allWidgetIds) {
			// Check if lockscreen/homescreen
			Bundle myOptions = appWidgetManager.getAppWidgetOptions (widgetId);
			int category = myOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY, -1);
			boolean isKeyguard = category == AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD;

			RemoteViews remoteViews = TapsAff.updateViews(null, settings, this, isKeyguard, widgetSize);
			
			appWidgetManager.updateAppWidget(widgetId, remoteViews);
		}
		editor = settings.edit();
		editor.putBoolean("viewsUpdated", true);
		editor.commit();
	}

	private void setColour(RemoteViews remoteViews, boolean hasText) {
		if(settings.getString("textColour", "Light").equals("Light")) {
			// Dunkel oder Licht
			if(hasText)
				remoteViews.setTextColor(R.id.text, getResources().getColor(R.color.light_font));
			remoteViews.setTextColor(R.id.temp, getResources().getColor(R.color.light_font_temp));
		} else {
			if(hasText)
				remoteViews.setTextColor(R.id.text, getResources().getColor(R.color.dark_font));
			remoteViews.setTextColor(R.id.temp, getResources().getColor(R.color.dark_font_temp));
		}
	}

	@Override
	public void onConnectionFailed(ConnectionResult arg0) {
	}

	@Override
	public void onConnected(Bundle arg0) {
		try {
			myLocation = myLocationClient.getLastLocation();
		} catch (IllegalStateException e) {
			myLocationClient.connect();
			e.printStackTrace();
		}
		if(myLocation!=null) {
			fetchWeatherForLocation(myLocation);
		} else {
			//request an update and listen callback.
			myLocationClient.requestLocationUpdates(LocationRequest.create(), this);
		}
	}
	
	@Override
	public void onLocationChanged(Location location) {
		myLocationClient.removeLocationUpdates(this);
		fetchWeatherForLocation(location);
	}
	
	private void fetchWeatherForLocation(Location l) {
		new GetWeatherTask().execute(l, this,settings);
	}

	@Override
	public void onDisconnected() {
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
}